import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) {
		if (args.length != 1) {
			System.out.println("Usage: java Server <port>");
			System.exit(-1);
		}
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		try {
			serverSocket = new ServerSocket(Integer.parseInt(args[0]));
			while (true) {
				clientSocket = serverSocket.accept();
				DataInputStream inputStream = new DataInputStream(
						clientSocket.getInputStream());
				DataOutputStream outputStream = new DataOutputStream(
						clientSocket.getOutputStream());
				boolean nextClient = false;
				while (!nextClient) {
					int length = (int) inputStream.readByte();
					System.out.println(length);
					switch (length) {
					case 1:
						byte numberByte = inputStream.readByte();
						System.out.println("Recieved: " + numberByte);
						outputStream.writeByte(++numberByte);
						System.out.println("Sent: " + numberByte);
						break;
					case 2:
						short numberShort = inputStream.readShort();
						System.out.println("Recieved: " + numberShort);
						outputStream.writeShort(++numberShort);
						System.out.println("Sent: " + numberShort);
						break;
					case 4:
						int numberInt = inputStream.readInt();
						System.out.println("Recieved: " + numberInt);
						outputStream.writeInt(++numberInt);
						System.out.println("Sent: " + numberInt);
						break;
					case 8:
						long numberLong = inputStream.readLong();
						System.out.println("Recieved: " + numberLong);
						outputStream.writeLong(++numberLong);
						System.out.println("Sent: " + numberLong);
						nextClient = true;
						break;
					}
				}
				clientSocket.close();
			}
		} catch (NumberFormatException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
